﻿using PTop.Application.Biz;
using PTop.Domain.Entity.Biz;
using System;
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace PTop.Web.Controllers
{
    public class CommonController : ControllerBase
    {
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="upload">附件</param>
        /// <param name="tableName">类别</param>
        /// <returns></returns>
        [HttpPost]
        [HandlerAjaxOnly]
        public ActionResult Upload(HttpPostedFileBase upload, string tableName)
        {
            if (upload == null)
            {
                return Error("没有文件");
            }
            var host = Request.Url.Host;
            var attachment = new AttachmentEntity();
            attachment.F_Type = tableName;
            attachment.F_Suffix = Path.GetExtension(upload.FileName);
            attachment.F_Name = Guid.NewGuid().ToString("N");
            attachment.F_Size = upload.InputStream.Length;
            attachment.F_CreatorTime = DateTime.Now;
            attachment.F_Path = attachment.GetFilePath(Request.MapPath("~/Upload"));
            try
            {
                upload.SaveAs(attachment.F_Path);
                //缩略图
                attachment.MakeThumbnail();
                new AttachmentApp().Save(attachment);
                return Success("操作成功。", attachment.GetWebPath("http://" + host + "/Upload"));
            }
            catch
            {
                return Error("上传异常");
            }
        }
    }
}